package com.cloud.business.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.business.dao.sys.SysStructMapper;
import com.cloud.business.dao.sys.SysUserMapper;
import com.cloud.business.entity.sys.SysStruct;
import com.cloud.business.entity.sys.SysUser;
import com.cloud.business.model.commonvm.DataTree;
import com.cloud.business.model.commonvm.DeletePost;
import com.cloud.business.model.commonvm.ResultMsg;
import com.cloud.business.model.sys.sysstructvm.SysStructModel;
import com.cloud.business.model.sys.sysstructvm.SysStructQueryModel;
import com.cloud.business.model.sys.sysstructvm.SysStructTree;
import com.cloud.business.service.sys.ISysStructService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 系统组织架构 服务实现类
 * </p>
 *
 * @author dh
 * @since 2020-03-21
 */
@Service
public class SysStructServiceImpl extends ServiceImpl<SysStructMapper, SysStruct> implements ISysStructService {
    @Resource
    private SysStructMapper sysStructMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    //region 获取分页列表

    /**
     * 获取分页列表
     *
     * @param sysStructQueryModel
     * @param page
     * @param msg
     * @throws Exception
     */
    @Override
    public void getListByPage(SysStructQueryModel sysStructQueryModel, IPage<SysStruct> page, ResultMsg msg) throws Exception {
        QueryWrapper<SysStruct> sysStructQueryWrapper = new QueryWrapper<>();
        sysStructQueryWrapper.lambda().like(!StringUtils.isEmpty(sysStructQueryModel.getQueryStr()), SysStruct::getName, sysStructQueryModel.getQueryStr())
                .orderByAsc(SysStruct::getSort);
        sysStructMapper.selectPage(page, sysStructQueryWrapper);
        msg.setMsg("获取成功");
    }
    //endregion

    //region 创建

    /**
     * 创建
     *
     * @param sysStruct
     * @param msg
     * @return
     * @throws Exception
     */
    @Override
    public Integer create(SysStruct sysStruct, ResultMsg msg) throws Exception {
        Date now = new Date();
        sysStruct.setCreateTime(now);
        sysStruct.setModificationTime(now);
        int count = sysStructMapper.insert(sysStruct);
        msg.setMsg("创建成功");
        return sysStruct.getObjectId();
    }
    //endregion

    //region 更新

    /**
     * 更新
     *
     * @param sysStruct
     * @param msg
     * @return
     * @throws Exception
     */
    @Override
    public Integer update(SysStruct sysStruct, ResultMsg msg) throws Exception {
        Date now = new Date();
        SysStruct SysStructOld = sysStructMapper.selectById(sysStruct.getObjectId());
        SysStructOld.setName(sysStruct.getName());
        SysStructOld.setPid(sysStruct.getPid());
        SysStructOld.setIsEnable(sysStruct.getIsEnable());
        SysStructOld.setRemark(sysStruct.getRemark());
        SysStructOld.setModificationTime(now);

        int count = sysStructMapper.updateById(sysStruct);
        msg.setMsg("更新成功");
        return sysStruct.getObjectId();
    }
    //endregion

    //region 获取单条

    /**
     * 获取单条
     *
     * @param operationId
     * @param objectId
     * @param msg
     * @return
     * @throws Exception
     */
    @Override
    public SysStruct getById(Integer operationId, Integer objectId, ResultMsg msg) throws Exception {
        SysStruct sysStruct = sysStructMapper.selectById(objectId);
        msg.setMsg("获取成功");
        return sysStruct;
    }
    //endregion

    //region 批量删除

    /**
     * 批量删除
     *
     * @param deletePost
     * @param msg
     * @return
     * @throws Exception
     */
    @Override
    public int deleteByList(DeletePost deletePost, ResultMsg msg) throws Exception {
        // 判断是否有孩子节点
        int childCnt = sysStructMapper.getCntByPids(deletePost.getKeyValues());
        if (childCnt > 0) {
            throw new Exception("删除失败，要删除的数据有子数据");
        }
        //判断是否关联用户
        Integer userCount = sysStructMapper.checkRelatedUser(deletePost.getKeyValues());
        if (userCount > 0) {
            throw new Exception("删除失败，要删除的数据有关联用户");
        }
        msg.setMsg("删除成功");
        int count = sysStructMapper.deleteBatchIds(deletePost.getKeyValues());
        if (count <= 0) {
            throw new Exception("删除失败");
        }
        return count;
    }
    //endregion

    //region 获取部门树

    /**
     * 获取部门树
     *
     * @param operationId
     * @param pkSysStruct
     * @return
     */
    @Override
    public List<SysStructTree> getSysStructsTree(Integer operationId, Integer pkSysStruct, Boolean isEnable) {

        List<SysStructTree> sysStructTreeList = new ArrayList<>();
        if (pkSysStruct == null) {
            pkSysStruct = 0;
        }

        List<SysStructModel> sysStructTrees = sysStructMapper.getSysStructTreeList(pkSysStruct);
        sysStructTrees.forEach(sysStruct -> {
            SysStructTree sysStructTree = new SysStructTree() {
                {
                    setId(sysStruct.getObjectId());
                    setText(sysStruct.getName());
                    setRemark(sysStruct.getRemark());
                    setParentid(sysStruct.getPid());
                    setParentName(sysStruct.getParentName());
                    setCode(sysStruct.getCode());
                    setCreateTime(sysStruct.getCreateTime());
                    setIsEnable(sysStruct.getIsEnable());
                    List<SysStructTree> children = getSysStructsTree(operationId, sysStruct.getObjectId(), isEnable);
                    setChildren(children);
                }
            };
            sysStructTreeList.add(sysStructTree);
        });

        return sysStructTreeList;
    }
    //endregion

    //region 获取部门树下人员

    /**
     * 获取部门树下人员
     *
     * @param operationId
     * @param pkSysStruct
     * @return
     */
    @Override
    public List<DataTree> getStructUserTree(Integer operationId, Integer pkSysStruct) {

        List<DataTree> sysStructTreeList = new ArrayList<>();
        QueryWrapper<SysStruct> sysStructQueryWrapper = new QueryWrapper<>();
        if (pkSysStruct == null) {
            pkSysStruct = 0;
        }
        sysStructQueryWrapper.lambda().eq(SysStruct::getPid, pkSysStruct)
                .orderByAsc(SysStruct::getSort);

        List<SysStruct> sysStructList = sysStructMapper.selectList(sysStructQueryWrapper);

        if (sysStructList.size() <= 0) {
            //获取用户返回
            QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
            sysUserQueryWrapper.lambda().eq(SysUser::getStructId, pkSysStruct);
            List<SysUser> sysUserList = sysUserMapper.selectList(sysUserQueryWrapper);
            Integer finalPkSysStruct = pkSysStruct;
            sysUserList.forEach(sysUser -> {
                DataTree sysStructTree = new DataTree() {
                    {
                        setId(sysUser.getObjectId());
                        setText(sysUser.getTrueName());
                        setType("user");
                        setParentid(finalPkSysStruct);
                    }
                };
                sysStructTreeList.add(sysStructTree);
            });
        } else {
            sysStructList.forEach(sysStruct -> {
                DataTree sysStructTree = new DataTree() {
                    {
                        setId(sysStruct.getObjectId());
                        setText(sysStruct.getName());
                        setParentid(sysStruct.getPid());
                        setType("struct");
                        List<DataTree> children = getStructUserTree(operationId, sysStruct.getObjectId());
                        setChildren(children);
                    }
                };
                sysStructTreeList.add(sysStructTree);
            });
        }
        return sysStructTreeList;
    }
    //endregion
}
